﻿using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;
using Newtonsoft.Json;
using SIG.Infrastructure.Configs;
using SIG.Model.Identity;
using SIG.WebMVC.App_Start;
using SIG.WebMVC.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Security.Claims;
using System.Web;
using System.Web.Helpers;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Security;

namespace SIG.WebMVC
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
          

            AreaRegistration.RegisterAllAreas();

            //   GlobalConfiguration.Configure(WebApiConfig.Register);
            // Register global filter
         
          // GlobalFilters.Filters.Add(new SIGActionFilterAttribute());
          // RegisterGlobalFilters(GlobalFilters.Filters);

            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

            //log config
            log4net.Config.XmlConfigurator.Configure();
            log4net.GlobalContext.Properties["user"] = new HttpContextUserNameProvider();


            // log4net.Config.XmlConfigurator.Configure(new FileInfo(Server.MapPath("~/Web.config")));


            // AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;

           

        }


        protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
        {
            HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
            if (authCookie != null)
            {

                FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

                CustomPrincipalSerializeModel serializeModel = JsonConvert.DeserializeObject<CustomPrincipalSerializeModel>(authTicket.UserData);
                CustomPrincipal newUser = new CustomPrincipal(authTicket.Name);
                newUser.UserId = serializeModel.UserId;
                newUser.RealName = serializeModel.RealName;
                newUser.Roles = serializeModel.Roles;
                newUser.Avatar = serializeModel.Avatar;
                //newUser.Menus = serializeModel.Menus;

                HttpContext.Current.User = newUser;
            }

        }
    }
}
